package java8.xml.dom;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;

/**
 * @author 周宇
 * @create 2020-08-28 14:50
 */
public class DomDemo {
    public static void main(String[] args) throws Exception {
        //DOM解析XML文件步骤
        //1、创建解析器工厂对象
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        //2、解析器工厂对象创建解析器对象
        DocumentBuilder builder = factory.newDocumentBuilder();
        //3、解析器对象指定XML文件创建Document对象
        Document doc = builder.parse(new File("src/main/resources/xml/book.xml"));
        //4、以Document对象为起点操作DOM树
        NodeList nodelist = doc.getChildNodes();

        //打印节点数
        //System.out.println(nodelist.getLength());
        //打印节点名称
        Node root = nodelist.item(0);
        System.out.println(root.getNodeName());
        //得到所有子节点 //注意：XML中的空 也算节点个数
        NodeList childNodes = root.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {
            //得到其中的一个子节点对象
            Node item = childNodes.item(i);
            if (item.getNodeType() == Node.ELEMENT_NODE) {//1 解析元素
                Element ele = (Element) item;
                //根据属性名得到属性值
                String id = ele.getAttribute("id");
                System.out.println(id);
            }

            NodeList childNodes2 = item.getChildNodes();
            for (int j = 0; j < childNodes2.getLength(); j++) {
                Node item2 = childNodes2.item(j);
                if (item2.getNodeType() == Node.ELEMENT_NODE) {
                    //:getTextContent 表示获取全部文本内容
                    String title = item2.getTextContent();
                    System.out.println(title);
                }
            }
        }
    }
}
